package com.dycong.common.leetcode.any;

import com.dycong.common.leetcode.ds.LinkedNode;

/**
 * 作用描述:
 *
 * @author dycong
 * @date 2020/1/3 8:53
 */
public class LinkedList<T> {

    private int count;
    private LinkedNode<T> head;

    public LinkedList() {
        this.count = 0;
        this.head = new LinkedNode<T>(null);
    }

    private boolean add0(int index, T t) {
        if (index > count) {
            throw new IllegalStateException();
        }
        LinkedNode<T> pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        LinkedNode<T> cur = new LinkedNode<>(t);
        cur.next = pre.next;
        pre.next = cur;
        count++;
        return true;
    }

    private boolean remove0(int index) {
        if (index > count) {
            throw new IllegalStateException();
        }
        LinkedNode<T> pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        LinkedNode<T> waitRv = pre.next;

        pre.next = waitRv == null ? null : waitRv.next;
        count--;
        waitRv = null;
        return true;
    }

    public boolean removeFirst() {
        return remove0(0);
    }


    public boolean removeLast() {
        return remove0(count-1);
    }


    public boolean add(T t) {
        return add0(0, t);
    }

    public boolean add(int index, T t) {
        return add0(index, t);
    }

    public int size() {
        return count;
    }

    public boolean isEmpty() {
        return count == 0;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder(10);
        LinkedNode node = head;
        while (node.next != null) {
            builder.append(node.next.val)
                    .append(",");
            node = node.next;
        }


        return builder.toString();
    }

    public static void main(String[] args) {
        LinkedList<Integer> linkedList = new LinkedList<>();
        for (int i = 0; i < 5; i++) {
            linkedList.add(i);
            System.out.println(linkedList);
        }

        //在索引为2的地方添加元素666
        linkedList.add(2, 666);
        System.out.println(linkedList);

        //删除索引为2的元素
        linkedList.removeFirst();
        System.out.println(linkedList);

        //删除链表第一个元素
        linkedList.removeFirst();
        System.out.println(linkedList);

        //删除链表最后一个元素
        linkedList.removeLast();
        System.out.println(linkedList);
    }

}
